import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin

import re
from threading import Thread

import nltk
from nltk.featstruct import FeatStruct
from nltk.draw.tree import *

import askmanager

class CanvasThread(Thread):
    def __init__(self, parsedSentence):
        Thread.__init__(self)
        self.parsedSentence = parsedSentence
    
    def run(self):
        sentree = createTree(self.parsedSentence)
        cf = CanvasFrame()
        tc = TreeWidget(cf.canvas(), sentree, draggable=1,  
                      #node_font=('helvetica', -14, 'bold'), 
                      #leaf_font=('helvetica', -12, 'italic'), 
                      #roof_fill='white', roof_color='black', 
                      leaf_color='green4', node_color='blue2',
                      xspace=10,yspace=10) 
        cf.add_widget(tc,10,10) 
        cf.mainloop()         

class SentencesListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
        ListCtrlAutoWidthMixin.__init__(self)
        self.parent = parent
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelect)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnActivate)
        self.ct = None
        
    def OnSelect(self, event):
        item = self.GetItem(event.GetIndex(), 0)
        
        formattedSent = self.parent.askManager.parser.formatParsedSentence(self.parent.parsedSentences[event.GetIndex()])
        self.parent.info.Clear()
        self.parent.info.AppendText(formattedSent)
        
    def OnActivate(self, event):
        sentree = createTree(self.parent.parsedSentences[event.GetIndex()])
        cf = CanvasFrame()
        tc = TreeWidget(cf.canvas(), sentree, draggable=1,  
                      #node_font=('helvetica', -14, 'bold'), 
                      #leaf_font=('helvetica', -12, 'italic'), 
                      #roof_fill='white', roof_color='black', 
                      leaf_color='green4', node_color='blue2',
                      xspace=10,yspace=10) 
        cf.add_widget(tc,10,10) 
        cf.mainloop() 
        
        ##if (self.ct):
        ##    self.ct.exit()
        ##self.ct = CanvasThread(self.parent.parsedSentences[event.GetIndex()])
        ##self.ct.start()
       

class ParsedSentencesPanel(wx.Panel):
    
    def __init__(self, parent, parsedSentences=None, askManager=None):
        wx.Panel.__init__(self, parent)
        self.parsedSentences = parsedSentences
        self.askManager = askManager

        vbox = wx.BoxSizer(wx.VERTICAL)
        
        self.listCtrl = SentencesListCtrl(self)
        self.listCtrl.InsertColumn(0, 'Col 1')
        #self.listCtrl.SetColumnWidth(1, 200)
        for parsed_sentence in self.parsedSentences:
            self.listCtrl.InsertStringItem(self.listCtrl.GetItemCount(), str(parsed_sentence))
        
        self.info = wx.TextCtrl(self, -1, 'Description', style=wx.TAB_TRAVERSAL|wx.TE_MULTILINE|wx.TE_LINEWRAP)
        
        vbox.Add(self.listCtrl, 2, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
        vbox.Add(self.info, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
        
        self.SetSizer(vbox)
      
class QuestionPanel(wx.Panel):
    
    def __init__(self, parent, data):
        wx.Panel.__init__(self, parent)
        self.parent = parent
        
        self.textctrl = wx.TextCtrl(self, -1, data, style=wx.TAB_TRAVERSAL|wx.TE_MULTILINE|wx.TE_LINEWRAP)        

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.textctrl, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
        self.SetSizer(vbox)
    
class DebugPage(wx.Panel):
    
    def __init__(self, parent, askManager):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent
        self.askManager = askManager
        pass
     
def createTree(parsed_sentence):
    """
        Creates a FeatStruct Tree from a parsedsentence
    """
    sentree = nltk.tree.Tree("S", children=[])
    for part in parsed_sentence:
        # first element is the type
        # the following element are tuples
        childTree = nltk.tree.Tree(part[0], children=[]) 
        sentree.append(childTree)
        #tree.children.append(childTree)
        for taggedpart in part[1:]:
            # '([cat=NP] [lex=the] [lex=dog])'
            #tagNode = nltk.tree.Tree(str(taggedpart), children=[])
            #tagNode = nltk.tree.Tree.parse('([cat=NP] [lex=the] [lex=dog])',parse_node=FeatStruct, parse_leaf=FeatStruct)
            type = taggedpart[0]
            p = re.compile(r'[,?!.`"]')
            type = p.sub( '', type)

            brownTag = taggedpart[1]
            conllTag = taggedpart[2]
            stringval = "(%s[brown='%s',conll='%s'])" % (type, brownTag, conllTag)
            #tagNode = nltk.tree.Tree.parse(stringval,parse_node=FeatStruct, parse_leaf=FeatStruct)
            tagNode = nltk.tree.Tree.parse(stringval,parse_node=FeatStruct)
            #tagNode = nltk.tree.Tree('([cat=NP] [lex=the] [lex=dog])')
            childTree.append(tagNode)   
    return sentree 